<?php

namespace App\Http\Controllers;

use App\Content;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class HomeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $req)
    {
//        $contents = DB::table('contents')->get();
        $contents = Content::all();
        return view('content_index', ['contents' => $contents]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data = $request->except('_token');
        $bool = Content::create($data);
        return redirect('content');

    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $data = Content::find($id);
        return view('content_modify')->with('data', $data);
//        return view("content_modify", compact('data'));
//        return view("content_modify", ['data' => $data]);

    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $input = $request->except('_token','_method');
        Content::find($id)->update($input);
        return redirect('content');

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {

    }

    public function delete($id)
    {
        $result = Content::destroy($id);
        return redirect('content');
    }

    public function add(Request $request){
        $validatedData = $request->validate([
            'data' => 'required',
            'photo' => 'required'
        ],[
            'data.required' => '内容不能为空',
            'photo.required' => '图片不能为空',
        ]);

        $file = $request->file('photo');
        $file_path = "";
        if($file->getMimeType()=='image/jpeg'){
            $file_path = $file->store('photo');
        }
        $content = $request->input('data');

        $contents = new Content;
        $contents->data = $content;
        $contents->photo = $file_path;
        $contents->save();
        return redirect('content');
    }
}
